﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sinacor.Infra.Core.Licensing;
using System.Text.RegularExpressions;
using System.Net.Mail;

namespace Sinacor.Infra.Core.Licensing
{
    public partial class LicensingApplication : Form
    {
        #region Campos
        int alturaWindow;
        int larguraWindow;

        Common common;
        OpenFileDialog ofd = null;
        SaveFileDialog sfd = null;

        Business.Licenca bussinesLicenca;
        Business.Empresa bussinesEmpresa;
        Business.Modulo bussinesModulo;

        Licensing pesquisaLicenca;
        Company pesquisaCompany;

        List<Licensing> listaLicenca;
        List<Licensing> listaLicencaBKP;

        Company company;
        List<Company> listaEmpresa;
        List<Company> listaCompany;
        List<String> listaCNPJ;

        List<Module> listaModulos;

        Licensing licensing;
        Description description;
        ConsultarHistorico consultarHistorico;
        CadastroEmpresa companyAplication;

        int? indiceLegalIdRegistrations;
        int? indiceLicensing;

        string ownerlegalregistrationid;
        string goodthru;

        bool atualizarDataModulos;

        string codeCNPJ;

        #endregion


        #region Construtor
        public LicensingApplication()
        {
            InitializeComponent();

            alturaWindow = this.Height;
            larguraWindow = this.Width;

            company = new Company();
            listaCNPJ = new List<String>();
            pesquisaCompany = new Company();
            bussinesEmpresa = new Business.Empresa();
            bussinesModulo = new Business.Modulo();

            description = new Description();
            listaLicenca = new List<Licensing>();
            listaLicencaBKP = new List<Licensing>();

            listaEmpresa = bussinesEmpresa.Selecionar(pesquisaCompany);

            CarregarEmpresa();

            listaModulos = bussinesModulo.Selecionar();

            common = new Common();
            atualizarDataModulos = true;

            codeCNPJ = "";
        }
        #endregion

        #region Evento

        #region Dados de Licenciamento

        private void LicensingApplication_Resize(object sender, EventArgs e)
        {
            this.Height = alturaWindow;
            this.Width = larguraWindow;
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            #region Limpar Dados

            atualizarDataModulos = false;

            indiceLicensing = null;
            indiceLegalIdRegistrations = null;

            #region Pesquisa
            mkdTxtCNPJ.Text = "";
            txtIdLicenca.Text = "";
            dtpDataCriacao.Value = DateTime.Now;
            dtpDataCriacao.Checked = false;

            cboTipoLicenca.SelectedItem = "";
            cboTipoLicencaCad.SelectedItem = "";
            dgvLicenca.DataSource = null;

            btnDelete.Enabled = false;
            btnExportar.Enabled = false;
            #endregion

            #region Licensed Modules
            cboOwnerLegalRegistrationId.DataSource = null;
            dtpGoodThru.Value = DateTime.Now;
            dtpGoodThru.Checked = false;

            cboEmpresa.SelectedIndex = -1;
            mtxtLegalRegistrationId.Clear();
            txtCompanyIdSinacor.Clear();

            DesabilitaChecksModulosMais();
            chkKernel.Checked = false;
            dgvLegalIdRegistrations.DataSource = null;

            licensing = new Licensing();
            licensing.Description = new Description { TypeDescription = TypeDescription.Incluir };

            listaLicenca = new List<Licensing>();

            indiceLegalIdRegistrations = null;
            chkModulo.Checked = false;
            #endregion
            atualizarDataModulos = true;
            #endregion

            CarregaListaLicenca();

            dgvLicenca.AutoGenerateColumns = false;
            dgvLicenca.DataSource = listaLicenca;

            indiceLicensing = null;
            indiceLegalIdRegistrations = null;

            dgvLicenca_CellMouseClick(dgvLicenca, null);
        }

        private void btnRemover_Click(object sender, EventArgs e)
        {
            int indice = -1;
            if (dgvLegalIdRegistrations.CurrentRow != null)
            {
                if (dgvLegalIdRegistrations.CurrentRow.Selected)
                {
                    indice = dgvLegalIdRegistrations.CurrentRow.Index;

                    if (licensing.Companies.Count > 0)
                    {
                        dgvLegalIdRegistrations.DataSource = null;
                        licensing.Companies.RemoveAt(indice);
                    }
                    else
                    {
                        licensing.Companies = (List<Company>)dgvLegalIdRegistrations.DataSource;
                        licensing.Companies.RemoveAt(indice);
                        dgvLegalIdRegistrations.DataSource = null;
                    }
                    dgvLegalIdRegistrations.AutoGenerateColumns = false;
                    dgvLegalIdRegistrations.DataSource = licensing.Companies;


                    if (dgvLegalIdRegistrations.CurrentRow != null)
                        dgvLegalIdRegistrations.CurrentRow.Selected = false;

                    AtualizaListaCNPJ();

                    atualizarDataModulos = false;

                    LimparModuloMais();
                    LimparDatas();
                    chkModulo.Checked = false;
                    atualizarDataModulos = true;

                    if (dgvLegalIdRegistrations.CurrentRow != null)
                    {
                        indiceLegalIdRegistrations = null;
                        dgvLegalIdRegistrations_CellMouseClick(dgvLegalIdRegistrations, null);
                    }
                }
            }
            if (dgvLegalIdRegistrations.CurrentRow != null)
                indiceLegalIdRegistrations = dgvLegalIdRegistrations.CurrentRow.Index;
            else
                indiceLegalIdRegistrations = null;

        }
        private void btnSalvar_Click(object sender, EventArgs e)
        {

            #region Validação

            if (string.IsNullOrEmpty(cboTipoLicencaCad.Text))
            {
                MessageBox.Show("Informe o Tipo da Licença.");
                return;
            }

            if ((Treaty?)cboTipoLicencaCad.SelectedItem != Treaty.Trial)
            {

                if (indiceLegalIdRegistrations != null)
                {
                    if (!ValidaRegistroSelecionado(indiceLegalIdRegistrations.Value))
                        return;
                }

                if (cboOwnerLegalRegistrationId.SelectedValue != null)
                    ownerlegalregistrationid = common.DesformatarCNPJ(cboOwnerLegalRegistrationId.SelectedValue.ToString());
                else
                    ownerlegalregistrationid = "";



                if (dgvLegalIdRegistrations.DataSource == null)
                {
                    MessageBox.Show("Adicione uma empresa para poder associar CNPJ raiz.");
                    return;
                }


                if (string.IsNullOrEmpty(ownerlegalregistrationid))
                {
                    MessageBox.Show("Informe " + lblOwnerLegalRegistrationId.Text);
                    return;
                }

                if (dgvLegalIdRegistrations.DataSource == null)
                {
                    MessageBox.Show("Adicione uma Empresa");
                    return;
                }
            }
            else
                ownerlegalregistrationid = "0";

            #endregion

            if (dgvLegalIdRegistrations.CurrentRow != null)
            {
                if (dgvLegalIdRegistrations.CurrentRow.Selected)
                {
                    //PreencheDataVencimentoModulo();
                    AtualizaDadosEmpresa(dgvLegalIdRegistrations.CurrentRow.Index);
                }
            }

            if (dgvLegalIdRegistrations.DataSource != null)
            {
                licensing.Companies = (List<Company>)dgvLegalIdRegistrations.DataSource;

                foreach (var item in licensing.Companies)
                {
                    item.LegalRegistrationId = common.DesformatarCNPJ(item.LegalRegistrationId);
                }
            }

            switch (licensing.Description.TypeDescription)
            {
                case TypeDescription.Incluir:
                    #region Incluir

                    licensing.OwnerLegalRegistrationId = ownerlegalregistrationid;
                    licensing.Created = DateTime.Now;
                    licensing.GoodThru = dtpGoodThru.Value;
                    licensing.Companies = (List<Company>)dgvLegalIdRegistrations.DataSource;
                    licensing.Treaty = (Treaty?)cboTipoLicencaCad.SelectedItem;
                    licensing.Active = Sinacor.Infra.Core.Licensing.Active.Ativo;

                    licensing.Description.User = Environment.UserName;
                    licensing.Description.Annotation = "Comentário Incluir";

                    licensing = bussinesLicenca.Incluir(licensing);

                    licensing.Description.TypeDescription = TypeDescription.Incluir;

                    #endregion
                    break;
                case TypeDescription.Alterar:
                    #region Alterar

                    licensing.OwnerLegalRegistrationId = ownerlegalregistrationid;
                    licensing.Created = DateTime.Now;
                    licensing.GoodThru = dtpGoodThru.Value;
                    licensing.Companies = (List<Company>)dgvLegalIdRegistrations.DataSource;
                    List<Company> companies = new List<Company>();

                    for (int indice = 0; indice < dgvLegalIdRegistrations.Rows.Count; indice++)
                    {
                        // if (dgvLegalIdRegistrations.Rows[indice].Cells["Flag"].Value != null)
                        // {
                        licensing.Companies[indice].LegalRegistrationId = common.DesformatarCNPJ(licensing.Companies[indice].LegalRegistrationId);
                        companies.Add(licensing.Companies[indice]);
                        // }
                    }

                    licensing.Companies = companies;
                    licensing.Treaty = (Treaty?)cboTipoLicencaCad.SelectedItem;
                    licensing.Active = Sinacor.Infra.Core.Licensing.Active.Ativo;

                    licensing.Description.TypeDescription = TypeDescription.Alterar;
                    licensing.Description.User = Environment.UserName;
                    licensing.Description.Annotation = "Comentário Alterar";

                    bussinesLicenca.Alterar(licensing);
                    licensing.Companies = (List<Company>)dgvLegalIdRegistrations.DataSource;
                    licensing.Description.TypeDescription = TypeDescription.Alterar;
                    #endregion
                    break;
                default:
                    break;
            }

            #region Atualiza registro

            if (listaLicenca.Count == 0)
                listaLicenca = new List<Licensing>();

            switch (licensing.Description.TypeDescription)
            {
                case TypeDescription.Incluir:
                    if (dgvLicenca.DataSource != null)
                        listaLicenca = (List<Licensing>)dgvLicenca.DataSource;

                    listaLicenca.Add(licensing);
                    break;
                case TypeDescription.Alterar:
                    foreach (Licensing item in listaLicenca)
                    {
                        if (item.Id == licensing.Id)
                        {
                            item.OwnerLegalRegistrationId = licensing.OwnerLegalRegistrationId;
                            item.Created = licensing.Created;
                            item.Companies = licensing.Companies;

                            item.Modules = licensing.Modules;
                            item.Description = licensing.Description;
                            item.Treaty = licensing.Treaty;
                        }
                    }
                    break;
                default:
                    break;
            }

            dgvLicenca.AutoGenerateColumns = false;
            dgvLicenca.DataSource = null;
            dgvLicenca.DataSource = listaLicenca;

            if (dgvLicenca.CurrentRow != null)
                dgvLicenca.CurrentRow.Selected = false;

            if (dgvLegalIdRegistrations.CurrentRow != null)
                dgvLegalIdRegistrations.CurrentRow.Selected = false;

            #endregion

            atualizarDataModulos = false;
            #region Limpa Dados
            LimparDadosLicenciamentoPrincipal();
            LimparDadosLicenciamento();
            LimparModuloMais();

            LimparDatas();
            LimparDataVencimento();
            LimparGridLicenciamento();

            indiceLegalIdRegistrations = null;
            #endregion
            atualizarDataModulos = true;

            CarregaListaLicencaBKP();

            #region Mensagem

            switch (licensing.Description.TypeDescription)
            {
                case TypeDescription.Incluir:
                    MessageBox.Show("Inclusão realizada com sucesso.");
                    break;
                case TypeDescription.Alterar:
                    MessageBox.Show("Alteração realizada com sucesso.");
                    break;
                default:
                    break;
            }
            #endregion

            licensing = new Licensing();
            licensing.Description.TypeDescription = TypeDescription.Incluir;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult dlgRes = MessageBox.Show("Deseja excluir a Licença?", "Gerador de Licença", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dlgRes == DialogResult.No)
                return;

            licensing.Created = DateTime.Now;
            licensing.Description = new Description();
            licensing.Description.User = Environment.UserName;
            licensing.Description.Annotation = "Comentário Excluir";
            licensing.Description.TypeDescription = TypeDescription.Excluir;
            licensing.OwnerLegalRegistrationId = common.DesformatarCNPJ(licensing.OwnerLegalRegistrationId);


            bussinesLicenca.Excluir(licensing);

            listaLicenca.RemoveAt(dgvLicenca.CurrentRow.Index);

            dgvLicenca.DataSource = null;
            dgvLicenca.AutoGenerateColumns = false;
            dgvLicenca.DataSource = listaLicenca;

            licensing = new Licensing();
            licensing.Description.TypeDescription = TypeDescription.Incluir;

            btnDelete.Enabled = false;

            atualizarDataModulos = false;
            #region Limpa Dados
            LimparDadosLicenciamentoPrincipal();
            LimparDadosLicenciamento();
            LimparModuloMais();

            LimparDatas();
            LimparGridLicenciamento();
            indiceLegalIdRegistrations = null;
            #endregion
            atualizarDataModulos = true;

            if (dgvLicenca.CurrentRow != null)
                dgvLicenca.CurrentRow.Selected = false;

            MessageBox.Show("Licença excluida com sucesso.");
        }

        private void btnHistorico_Click(object sender, EventArgs e)
        {
            if (licensing.Id == null)
                consultarHistorico = new ConsultarHistorico(this);
            else
                consultarHistorico = new ConsultarHistorico(this, licensing);

            consultarHistorico.Show();
        }
        private void btnExportar_Click(object sender, EventArgs e)
        {
            if (sfd == null)
            {
                sfd = new SaveFileDialog();
                sfd.InitialDirectory = @"C:\";
                sfd.DefaultExt = "lic";
                sfd.Filter = "Sinacor License File(*.lic)|*.lic";
                sfd.AddExtension = true;
                sfd.CheckPathExists = true;
                sfd.OverwritePrompt = true;
                sfd.RestoreDirectory = false;
                sfd.ValidateNames = true;
            }

            DialogResult dr = sfd.ShowDialog();

            if (DialogResult.OK == dr)
            {
                Sinacor.Infra.Core.Licensing.LicensingGenerator licensingGenerator = new Sinacor.Infra.Core.Licensing.LicensingGenerator();

                if (licensing.Treaty == Treaty.Trial)
                    licensing.GoodThru = dtpGoodThru.Value;

                licensing.OwnerLegalRegistrationId = common.DesformatarCNPJ(licensing.OwnerLegalRegistrationId);

                foreach (var item in licensing.Companies)
                {
                    item.LegalRegistrationId = common.DesformatarCNPJ(item.LegalRegistrationId);
                }

                SignedLicensing signedLicensing = licensingGenerator.Generate(licensing);
                signedLicensing.SaveMappedLicensingFile(sfd.FileName);
            }
            MessageBox.Show("Arquivo exportado com sucesso");
        }

        private void btnNewCompany_Click(object sender, EventArgs e)
        {
            if (indiceLegalIdRegistrations != null)
            {
                if (!ValidaRegistroSelecionado(indiceLegalIdRegistrations.Value))
                    return;
            }

            if (dgvLegalIdRegistrations.DataSource != null)
            {
                AtualizaDadosEmpresa(dgvLegalIdRegistrations.CurrentRow.Index);
                dgvLegalIdRegistrations.CurrentRow.Selected = false;
            }
            mtxtLegalRegistrationId.Clear();
            atualizarDataModulos = false;
            cboEmpresa.SelectedIndex = -1;

            txtCompanyIdSinacor.Clear();
            LimparModuloMais();
            LimparDatas();
            LimparDataVencimento();

            SelecionarDesSelecionar(false);
            indiceLegalIdRegistrations = null;
            atualizarDataModulos = true;
        }
        private void btnAdicionar_Click(object sender, EventArgs e)
        {
            DateTime goodThru = dtpGoodThru.Value;
            int companyIdSinacor = string.IsNullOrEmpty(txtCompanyIdSinacor.Text) ? 0 : Convert.ToInt32(txtCompanyIdSinacor.Text);
            string companyName = "";
            int companyId = 0;

            Company empresaAux = ((Company)cboEmpresa.SelectedItem);

            if (empresaAux != null)
            {
                if (empresaAux.CompanyId.HasValue)
                {
                    companyId = empresaAux.CompanyId.Value;
                    companyName = empresaAux.Name;
                }
            }
            string legalregistrationid = common.ValorControle(mtxtLegalRegistrationId);

            Company company = null;

            if (!ValidarDadosLicenciamento())
                return;

            List<Module> lisModule = ValidarEmpresaModulo();

            if (lisModule.Count == 0)
                return;
            else
            {
                //                       PreencheDataVencimentoModulo();
                lisModule = ValidarEmpresaModulo();
            }


            listaCompany = (List<Company>)dgvLegalIdRegistrations.DataSource;

            Company companyE = null;

            if (listaCompany != null)
                companyE = listaCompany.Find(match => match.LegalRegistrationId == mtxtLegalRegistrationId.Text && match.SinacorCompanyId.Value == companyIdSinacor);


            if (companyE != null)
            {
                MessageBox.Show("Empresa já adicionada.");
                return;
            }


            #region Company
            company = new Company();

            company.CompanyId = companyId;
            company.SinacorCompanyId = companyIdSinacor;
            company.Name = companyName;
            company.LegalRegistrationId = legalregistrationid;
            #endregion

            company.Modules = lisModule;// listModuleCompany;

            if (listaCompany == null)
                listaCompany = new List<Company>();

            listaCompany.Add(company);

            dgvLegalIdRegistrations.DataSource = null;
            dgvLegalIdRegistrations.AutoGenerateColumns = false;
            dgvLegalIdRegistrations.DataSource = listaCompany;

            atualizarDataModulos = false;

            #region Limpar Dados
            SelecionarDesSelecionar(false);
            LimparDadosLicenciamento();
            LimparModuloMais();
            LimparDatas();
            LimparDataVencimento();
            #endregion
            atualizarDataModulos = true;

            indiceLegalIdRegistrations = null;
            dgvLegalIdRegistrations.CurrentRow.Selected = false;

            AtualizaListaCNPJ();
        }

        private void cboEmpresa_SelectedIndexChanged(object sender, EventArgs e)
        {
            company = new Company();
            List<Company> listaCompanyAux = (List<Company>)dgvLegalIdRegistrations.DataSource;

            if (cboEmpresa.SelectedIndex > 0)
            {
                foreach (var item in ((List<Company>)cboEmpresa.DataSource))
                {
                    if (item.CompanyId.HasValue)
                    {
                        if (item.CompanyId.Value == ((Company)cboEmpresa.SelectedItem).CompanyId.Value)
                        {
                            company = item;
                            break;
                        }
                    }
                }
            }

            if (company.CompanyId.HasValue)
            {
                List<Company> ListCompanyE = null;


                mtxtLegalRegistrationId.Text = company.LegalRegistrationId;
                txtCompanyIdSinacor.Text = company.SinacorCompanyId.ToString();

                if (dgvLegalIdRegistrations.CurrentRow != null)
                {
                    if (dgvLegalIdRegistrations.CurrentRow.Selected)
                    {
                        if (listaCompanyAux != null)
                        {
                            ListCompanyE = new List<Company>();
                            foreach (var item in listaCompanyAux)
                            {
                                if (common.DesformatarCNPJ(item.LegalRegistrationId) == company.LegalRegistrationId && item.SinacorCompanyId == company.SinacorCompanyId)
                                {
                                    ListCompanyE.Add(item);
                                }
                            }
                        }
                        if (ListCompanyE != null)
                        {
                            AtualizaListaCNPJ();
                            if (ListCompanyE.Count > 1)
                            {
                                cboEmpresa.SelectedIndex = -1;
                                MessageBox.Show("Empresa já adicionada.");
                                return;
                            }
                        }
                    }
                }

            }
            else
            {
                mtxtLegalRegistrationId.Clear();
                txtCompanyIdSinacor.Clear();
            }
            if (listaCompany != null)
            {
                if (cboOwnerLegalRegistrationId.SelectedValue != null)
                {
                    string valorOwnerLegalRegistrationId = cboOwnerLegalRegistrationId.SelectedValue.ToString();
                    AtualizaListaCNPJ();

                    if (cboOwnerLegalRegistrationId.SelectedValue == null)
                    {
                        cboOwnerLegalRegistrationId.SelectedIndex = -1;
                    }
                    else
                    {
                        if (valorOwnerLegalRegistrationId != cboOwnerLegalRegistrationId.SelectedValue.ToString())
                            cboOwnerLegalRegistrationId.SelectedIndex = -1;
                    }
                }
            }

            if (dgvLegalIdRegistrations.CurrentRow != null)
            {
                if (dgvLegalIdRegistrations.CurrentRow.Selected)
                    dgvLegalIdRegistrations.CurrentRow.Cells["Name"].Value = company.Name;
            }

        }

        private void chkModulo_Click(object sender, EventArgs e)
        {
            CheckBox checkBox = (CheckBox)sender;

            DescricaoModulo(checkBox);

            SelecionarDesSelecionar(checkBox.Checked);
        }

        private void dtpGoodThru_ValueChanged(object sender, EventArgs e)
        {

        }
        private void dtpGoodThru_Leave(object sender, EventArgs e)
        {
            //if (atualizarDataModulos)
            //{
            //    PreencheDataVencimentoModulo();
            //}        
        }

        private void PreencheDataVencimentoModulo()
        {
            //if (dtpGoodThru.Checked && dtpGoodThru.Value.ToShortDateString() != DateTime.Now.ToShortDateString())
            if (dtpGoodThru.Checked)
            {
                if (MessageBox.Show("Deseja aplicar esta data a todos os módulos?", "Licensing", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    foreach (Control ctrl in this.groupModulos.Controls)
                    {
                        if (ctrl.GetType() == typeof(DateTimePicker))
                        {
                            if (((DateTimePicker)ctrl).Enabled)
                                ((DateTimePicker)ctrl).Value = dtpGoodThru.Value;
                        }
                    }
                }
            }
        }


        private void LicensingForm_Load(object sender, EventArgs e)
        {
            HabilitaDesabilitaBotoesMais(false);
            CarregarTipoLicenca();

            bussinesLicenca = new Business.Licenca();
            pesquisaLicenca = new Sinacor.Infra.Core.Licensing.Licensing();
            licensing = new Licensing();
            licensing.Description = new Description { TypeDescription = TypeDescription.Incluir };
        }

        private void mtxtOwnerLegalRegistrationId_Validated(object sender, EventArgs e)
        {
            mtxtLegalRegistrationId.Text = cboOwnerLegalRegistrationId.SelectedText;
        }
        private void OpenLicenseFile()
        {
            try
            {
                SignedLicensing signedLicensing;
                signedLicensing = new SignedLicensing();
                signedLicensing.LoadMappedLicensingFile(txtLicenseFileName.Text);

                listaLicenca = new List<Licensing>();

                Licensing licensingAux = bussinesLicenca.SelecionarLicencaAtual(signedLicensing.Licensing);

                if (licensingAux.Active != null)
                {
                    //Verificar se a licença foi excluida
                    if (licensingAux.Active.Value == Sinacor.Infra.Core.Licensing.Active.Inativo)
                    {
                        string mensagem = string.Format("A Licença: {0} está inativa deseja ir para tela de Histórico?", signedLicensing.Licensing.Id);
                        if (MessageBox.Show(mensagem, "Licensing", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            if (consultarHistorico != null)
                                consultarHistorico.Close();

                            consultarHistorico = new ConsultarHistorico(this, signedLicensing.Licensing);
                            consultarHistorico.Show();
                        }
                    }//Verificar o id histórico da Licença
                    else if (licensingAux.Description.Id != signedLicensing.Licensing.Description.Id)
                    {
                        string mensagem = string.Format("A Licença: {0} está desatualizada deseja ir para tela de Histórico?", signedLicensing.Licensing.Id);
                        if (MessageBox.Show(mensagem, "Licensing", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            if (consultarHistorico != null)
                                consultarHistorico.Close();

                            consultarHistorico = new ConsultarHistorico(this, signedLicensing.Licensing);
                            consultarHistorico.Show();
                        }
                    }
                }

                listaLicenca.Add(signedLicensing.Licensing);
                dgvLicenca.AutoGenerateColumns = false;
                dgvLicenca.DataSource = listaLicenca;

                indiceLicensing = null;
                indiceLegalIdRegistrations = null;

                dgvLicenca_CellMouseClick(dgvLicenca, null);
                CarregaListaLicencaBKP();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void txtCompanyName_TextChanged(object sender, EventArgs e)
        {
            if (dgvLegalIdRegistrations.CurrentRow != null)
            {
                if (dgvLegalIdRegistrations.CurrentRow.Selected)
                {
                    dgvLegalIdRegistrations.CurrentRow.Cells["Name"].Value = cboEmpresa.SelectedText;
                    //dgvLegalIdRegistrations.CurrentRow.Cells["Flag"].Value = "A";
                }
            }
        }

        private void mtxtLegalRegistrationId_TextChanged(object sender, EventArgs e)
        {
            if (dgvLegalIdRegistrations.CurrentRow != null)
            {
                if (dgvLegalIdRegistrations.CurrentRow.Selected)
                {
                    dgvLegalIdRegistrations.CurrentRow.Cells["LegalRegistrationId"].Value = mtxtLegalRegistrationId.Text;
                    //dgvLegalIdRegistrations.CurrentRow.Cells["Flag"].Value = "A";
                }
            }
        }
        private void txtCompanyIdSinacor_TextChanged(object sender, EventArgs e)
        {
            if (dgvLegalIdRegistrations.CurrentRow != null)
            {
                if (dgvLegalIdRegistrations.CurrentRow.Selected)
                {
                    int? companyIdSinacor;
                    if (string.IsNullOrEmpty(txtCompanyIdSinacor.Text))
                        companyIdSinacor = null;
                    else
                        companyIdSinacor = Convert.ToInt32(txtCompanyIdSinacor.Text);

                    dgvLegalIdRegistrations.CurrentRow.Cells["SinacorCompanyId"].Value = companyIdSinacor;
                    //dgvLegalIdRegistrations.CurrentRow.Cells["Flag"].Value = "A";
                }
            }
        }
        private void txtCompanyIdSinacor_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar))
                e.Handled = true;
        }
        #endregion

        #region License File
        private void btnAbrir_Click(object sender, EventArgs e)
        {
            if (ofd == null)
            {
                ofd = new OpenFileDialog();
                //ofd.InitialDirectory = @"C:\";
                ofd.Multiselect = false;
                ofd.Filter = "Sinacor License File(*.lic)|*.lic";
            }

            DialogResult dr = ofd.ShowDialog();

            if (dr == DialogResult.OK)
            {
                btnNovo_Click(sender, e);
                txtLicenseFileName.Text = ofd.FileName;
                OpenLicenseFile();
            }
        }
        private void btnNovo_Click(object sender, EventArgs e)
        {
            btnNovaPesquisa_Click(sender, e);

            //licensing = new Licensing();
            //licensing.Description.TypeDescription = TypeDescription.Incluir;

            //indiceLicensing = null;
            //indiceLegalIdRegistrations = null;

            //atualizarDataModulos = false;
            //txtLicenseFileName.Clear();
            //cboEmpresa.SelectedIndex = -1;

            //txtCompanyIdSinacor.Clear();
            //mtxtLegalRegistrationId.Clear();

            //cboOwnerLegalRegistrationId.DataSource = null;
            //listaCNPJ.Clear();

            //dgvLegalIdRegistrations.DataSource = null;
            //listaCNPJ.Clear();

            //LimparDatas();
            //LimparDataVencimento();

            //HabilitaDesabilitaBotoesMais(false);
            //DesabilitaChecksModulosMais();
            //atualizarDataModulos = true;

            //if (dgvLicenca.CurrentRow != null)
            //    dgvLicenca.CurrentRow.Selected = false;

        }
        #endregion

        #region Licensed Modules

        #region Modulos
        private void chkCadastroBasico_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkCadastroClientePlus, dtpDateCadastroCliente);
        }
        private void chkOrdensBovespa_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkOrdensBovespaPlus, dtpDateOrdensBovespa);
        }
        private void chkOrdensBmf_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkOrdensBmfPlus, dtpDateOrdensBMF);
        }

        private void chkTesouraria_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkTesourariaPlus, dtpDateTesouraria);
        }
        private void chkContaCorrente_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkContaCorrentePlus, dtpDateContaCorrente);
        }

        private void chkCustodia_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkCustodiaPlus, dtpDateCustodia);
        }
        private void chkFaturamentoBovespa_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkFaturamentoBovespaPlus, dtpDateFaturamentoBovespa);
        }
        private void chkFaturamentoBmf_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkFaturamentoBmfPlus, dtpDateFaturamentoBMF);
        }

        private void chkContabilidade_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkContabilidadePlus, dtpDateContabilidade);
        }
        private void chkApuracaoResultado_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkInformacoesApoioPlus, dtpDateInformacoesApoio);
        }
        private void chkContasPagar_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkContasPagarPlus, dtpDateContasPagar);
        }

        private void chkDBM_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkSolicitacoesPlus, dtpDateSolicitacoes);
        }
        private void chkBTC_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkFaturamentoBTCPlus, dtpDateFaturamentoBTC);
        }
        private void chkIFT_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkIFTPlus, dtpDateIFT);
        }

        private void chkAcompControle_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkAcompControlePlus, dtpDateAcompControle);
        }
        private void chkAcompLimites_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkAcompLimitesPlus, dtpDateAcompLimites);
        }
        private void chkCustodiaFiduciaria_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkCustodiaFiduciariaPlus, dtpDateCustodiaFiduciaria);
        }

        private void chkApuracaoIRRF_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkApuracaoIRRFPlus, dtpDateApuracaoIRRF);
        }
        private void chkGerArqBacen_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkGerArqBacenPlus, dtpDateGerArqBacen);
        }
        private void chkCtrlAcesso_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkCtrlAcessoPlus, dtpDateCtrlAcesso);
        }

        private void chkCompliance_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkCompliancePlus, dtpDateCompliance);
        }
        private void chkConef_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkConefPlus, dtpDateConef);
        }

        private void chkSinacorHub_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkSinacorHubPlus, dtpDateSinacorHub);
        }
        private void chkApurResultado_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkApurResultadoPlus, dtpDateApurResultado);
        }
        private void chkXFB_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkXFBPlus, dtpDateXFB);
        }

        private void chkOutros_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkOutrosPlus, dtpDateOutros);
        }

        private void chkInformacoesApoio_CheckedChanged(object sender, EventArgs e)
        {
            VerificaLicencaModulo(((CheckBox)sender), chkInformacoesApoioPlus, dtpDateInformacoesApoio);
        }
        private void chkKernelPlus_CheckedChanged(object sender, EventArgs e)
        {
            HabilitaDesabilitaBotoesMais(((CheckBox)sender).Checked);
            VerificaLicencaModulo(((CheckBox)sender), null, dtpDateKernel);
        }
        private void chkKernel_Click(object sender, EventArgs e)
        {

        }

        #endregion

        #region Mais
        private void chkCadastroBasicoPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkCadastroCliente.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkOrdensBovespaPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkOrdensBovespa.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkOrdensBmfPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkOrdensBmf.Checked = true;

            VerificaMaisSelecionado();
        }

        private void chkTesourariaPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkTesouraria.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkContaCorrentePlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkContaCorrente.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkCustodiaPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkCustodia.Checked = true;

            VerificaMaisSelecionado();
        }

        private void chkFaturamentoBovespaPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkFaturamentoBovespa.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkFaturamentoBmfPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkFaturamentoBmf.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkContabilidadePlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkContabilidade.Checked = true;

            VerificaMaisSelecionado();
        }

        private void chkContasPagarPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkContasPagar.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkDBMPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkSolicitacoes.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkBTCPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkFaturamentoBTC.Checked = true;

            VerificaMaisSelecionado();
        }

        private void chkIFTPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkIFT.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkAcompControlePlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkAcompControle.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkAcompLimitesPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkAcompLimites.Checked = true;

            VerificaMaisSelecionado();
        }

        private void chkCustodiaFiduciariaPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkCustodiaFiduciaria.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkApuracaoIRRFPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkApuracaoIRRF.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkInformacoesApoioPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkInformacoesApoio.Checked = true;

            VerificaMaisSelecionado();
        }

        private void chkGerArqBacenPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkGerArqBacen.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkCtrlAcessoPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkCtrlAcesso.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkCompliancePlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkCompliance.Checked = true;

            VerificaMaisSelecionado();
        }

        private void chkConefPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkConef.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkSinacorHubPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkSinacorHub.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkApurResultadoPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkApurResultado.Checked = true;

            VerificaMaisSelecionado();
        }

        private void chkXFBPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkXFB.Checked = true;

            VerificaMaisSelecionado();
        }
        private void chkOutrosPlus_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)sender).Checked)
                chkOutros.Checked = true;

            VerificaMaisSelecionado();
        }
        #endregion

        #endregion

        #region Pesquisa
        private void btnEditar_Click(object sender, EventArgs e)
        {
            Company companyAux = (Company)cboEmpresa.SelectedItem;

            if (companyAux == null)
                companyAplication = new CadastroEmpresa(this);
            else
            {
                if (companyAux.CompanyId.HasValue)
                    companyAplication = new CadastroEmpresa(this, company);
                else
                    companyAplication = new CadastroEmpresa(this);
            }

            companyAplication.Show();
        }

        private void btnPesquisar_Click(object sender, EventArgs e)
        {

            #region Pesquisa

            #region OwnerLegalRegistrationId
            pesquisaLicenca.OwnerLegalRegistrationId = common.ValorControle(mkdTxtCNPJ);

            if (string.IsNullOrEmpty(pesquisaLicenca.OwnerLegalRegistrationId))
                pesquisaLicenca.OwnerLegalRegistrationId = null;
            else
            {
                if (!common.ValidarCNPJ(pesquisaLicenca.OwnerLegalRegistrationId) && codeCNPJ != common.StrongCode)
                {
                    MessageBox.Show("CNPJ Inválido");
                    return;
                }
            }
            #endregion

            #region Id Licença
            if (string.IsNullOrEmpty(txtIdLicenca.Text))
                pesquisaLicenca.Id = null;
            else
                pesquisaLicenca.Id = Convert.ToInt32(txtIdLicenca.Text);
            #endregion

            #region Created
            if (!dtpDataCriacao.Checked)
                pesquisaLicenca.Created = null;
            else
                pesquisaLicenca.Created = Convert.ToDateTime(dtpDataCriacao.Text);
            #endregion

            #region Treaty

            if (string.IsNullOrEmpty(cboTipoLicenca.Text))
                pesquisaLicenca.Treaty = null;
            else
                pesquisaLicenca.Treaty = (Treaty?)cboTipoLicenca.SelectedItem;
            #endregion

            #endregion

            listaLicenca = bussinesLicenca.Selecionar(pesquisaLicenca);
            dgvLicenca.AutoGenerateColumns = false;
            dgvLicenca.DataSource = listaLicenca;

            CarregaListaLicencaBKP();

            indiceLicensing = null;

            if (listaLicenca.Count == 0)
                MessageBox.Show("Não foram encontrados dados que satisfaçam a pesquisa.");
            else
            {
                dgvLicenca_CellMouseClick(dgvLicenca, null);
                dgvLegalIdRegistrations_CellMouseClick(dgvLegalIdRegistrations, null);
                AtualizaListaCNPJ();

                if (dgvLicenca.CurrentRow != null)
                    indiceLicensing = dgvLicenca.CurrentRow.Index;
            }

        }
        public void btnNovaPesquisa_Click(object sender, EventArgs e)
        {
            atualizarDataModulos = false;

            indiceLicensing = null;
            indiceLegalIdRegistrations = null;

            #region Pesquisa
            mkdTxtCNPJ.Text = "";
            txtIdLicenca.Text = "";
            dtpDataCriacao.Value = DateTime.Now;
            dtpDataCriacao.Checked = false;

            cboTipoLicenca.SelectedItem = "";
            cboTipoLicencaCad.SelectedItem = "";
            dgvLicenca.DataSource = null;

            btnDelete.Enabled = false;
            btnExportar.Enabled = false;
            #endregion

            #region Licensed Modules
            cboOwnerLegalRegistrationId.DataSource = null;
            dtpGoodThru.Value = DateTime.Now;
            dtpGoodThru.Checked = false;

            cboEmpresa.SelectedIndex = -1;
            mtxtLegalRegistrationId.Clear();
            txtCompanyIdSinacor.Clear();

            DesabilitaChecksModulosMais();
            chkKernel.Checked = false;
            dgvLegalIdRegistrations.DataSource = null;

            licensing = new Licensing();
            licensing.Description = new Description { TypeDescription = TypeDescription.Incluir };

            listaLicenca = new List<Licensing>();
            listaLicencaBKP = new List<Licensing>();
            indiceLegalIdRegistrations = null;
            chkModulo.Checked = false;
            #endregion
            atualizarDataModulos = true;
        }

        private void dgvLicenca_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;
            if (grid.CurrentCell != null)
            {
                grid.Rows[grid.CurrentCell.RowIndex].Selected = true;
                dgvLicenca_RowHeaderMouseClick(sender, e);
            }

        }
        private void dgvLicenca_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (indiceLicensing.HasValue)
            {
                if (indiceLicensing.Value != dgvLicenca.CurrentRow.Index)
                {
                    if (indiceLegalIdRegistrations != null)
                    {
                        if (licensing.Treaty != Treaty.Trial)
                        {
                            if (!ValidaRegistroSelecionado(indiceLegalIdRegistrations.Value))
                            {
                                dgvLicenca.CurrentRow.Selected = false;
                                dgvLicenca.Rows[indiceLicensing.Value].Selected = true;
                                return;
                            }
                            AtualizaDadosEmpresa(indiceLegalIdRegistrations.Value);
                            LimparModuloMais();
                        }
                        else
                        {
                            dtpGoodThru.Value = licensing.GoodThru.Value;
                        }
                    }
                    #region Validação

                    if (dgvLegalIdRegistrations.Rows.Count == 0 && licensing.Treaty != Treaty.Trial)
                    {
                        MessageBox.Show("Adicione uma empresa para poder associar CNPJ raiz.");
                        dgvLicenca.CurrentRow.Selected = false;
                        dgvLicenca.Rows[indiceLicensing.Value].Selected = true;
                        return;
                    }

                    #endregion
                }
            }


            atualizarDataModulos = false;
            LimparModuloMais();
            dgvLegalIdRegistrations.DataSource = null;
            DataGridView grid = (DataGridView)sender;

            licensing = new Licensing();

            #region Cria a classe Licensing

            licensing.Id = Convert.ToInt32(grid.CurrentRow.Cells["LicensingId"].Value);
            licensing.OwnerLegalRegistrationId = grid.CurrentRow.Cells["CNPJ"].Value.ToString();
            licensing.Created = Convert.ToDateTime(grid.CurrentRow.Cells["DataCriacao"].Value);
            //licensing.GoodThru = Convert.ToDateTime(grid.CurrentRow.Cells["GoodThru"].Value);
            licensing.Treaty = (Treaty)grid.CurrentRow.Cells["TipoLicenca"].Value;
            licensing.Active = (Active)grid.CurrentRow.Cells["Status"].Value;
            licensing.Companies = (List<Company>)grid.CurrentRow.Cells["Empresa"].Value;

            licensing.Description = (Description)grid.CurrentRow.Cells["Historico"].Value;

            if (new Sinacor.Infra.Core.Licensing.Business.Licenca().Selecionar(new Licensing() { Id = licensing.Id, Created = null, OwnerLegalRegistrationId = null, Treaty = null }).Count > 0)
                licensing.Description.TypeDescription = TypeDescription.Alterar;
            else
                licensing.Description.TypeDescription = TypeDescription.Incluir;

            #endregion

            #region Preenche Dados de Licenciamento

            cboTipoLicencaCad.SelectedItem = licensing.Treaty.Value;
            dtpGoodThru.Value = DateTime.Now;
            dtpGoodThru.Checked = false;

            #endregion

            #region Preenche a Grid LegalIdRegistrations

            if (licensing.Treaty != Treaty.Trial)
            {
                indiceLegalIdRegistrations = null;

                listaCompany = (List<Company>)grid.CurrentRow.Cells["Empresa"].Value;

                dgvLegalIdRegistrations.AutoGenerateColumns = false;
                dgvLegalIdRegistrations.DataSource = listaCompany;
                dgvLegalIdRegistrations_CellMouseClick(dgvLegalIdRegistrations, null);

                AtualizaListaCNPJ();

                SelecionarOwnerLegalRegistrationId(licensing.OwnerLegalRegistrationId);
            }

            #endregion

            if (dgvLicenca.CurrentRow == null)
                indiceLicensing = null;
            else
                indiceLicensing = dgvLicenca.CurrentRow.Index;

            btnDelete.Enabled = true;
            btnExportar.Enabled = true;
            atualizarDataModulos = true;
        }
        private void dgvLicenca_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;

            foreach (DataGridViewRow row in grid.Rows)
            {
                row.Cells["CNPJ"].Value = common.FormatarCNPJ(row.Cells["CNPJ"].Value.ToString());
            }
        }

        private void dgvLegalIdRegistrations_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;
            List<Module> lisModule = null;

            int contadorModulo = 0;
            List<CheckBox> listCheckModulos = new List<CheckBox>();
            CheckBox checkbox1 = null;


            if (indiceLegalIdRegistrations != null)
            {
                if (indiceLegalIdRegistrations.Value != grid.CurrentRow.Index)
                {
                    if (!ValidaRegistroSelecionado(indiceLegalIdRegistrations.Value))
                        return;
                }
            }

            lisModule = (List<Module>)grid.CurrentRow.Cells["Modules"].Value;

            AtualizaDadosEmpresa(grid.CurrentRow.Index);
            LimparModuloMais();
            LimparDataVencimento();
            indiceLegalIdRegistrations = grid.CurrentRow.Index;

            #region Preenche Dados de Licenciamento

            for (int indice = 0; indice < listaEmpresa.Count; indice++)
            {
                if (!string.IsNullOrEmpty(listaEmpresa[indice].Name) && grid.CurrentRow.Cells["Name"].Value != null)
                {
                    if (listaEmpresa[indice].Name == grid.CurrentRow.Cells["Name"].Value.ToString())
                    {
                        cboEmpresa.SelectedIndex = indice;
                        break;
                    }
                }
            }

            if (grid.CurrentRow.Cells["LegalRegistrationId"].Value != null)
                mtxtLegalRegistrationId.Text = grid.CurrentRow.Cells["LegalRegistrationId"].Value.ToString();
            else
                mtxtLegalRegistrationId.Text = string.Empty;

            txtCompanyIdSinacor.Text = grid.CurrentRow.Cells["SinacorCompanyId"].Value == null ? "" : grid.CurrentRow.Cells["SinacorCompanyId"].Value.ToString();

            if (licensing.Treaty == Treaty.Trial)
            {
                txtCompanyIdSinacor.Text = string.Empty;
                mtxtLegalRegistrationId.Text = string.Empty;
                cboEmpresa.SelectedIndex = -1;
            }

            #endregion

            //Seleciona os Checkboxes e DatetimePicker através dos Modulos
            chkModulo.Checked = false;
            #region Modulos

            foreach (Control ctrl in groupModulos.Controls)
            {
                if (ctrl.GetType() == typeof(CheckBox))
                {
                    checkbox1 = ((CheckBox)ctrl);
                    if (checkbox1.Appearance == Appearance.Normal)
                    {
                        Module module = lisModule.Find(match => match.Monogram == checkbox1.Tag.ToString());

                        if (module != null)
                        {
                            checkbox1.Checked = true;

                            string maismodulo = checkbox1.Name + "Plus";
                            Control[] controleMais = groupModulos.Controls.Find(maismodulo, true);
                            CheckBox checkbox2 = null;

                            if (controleMais.Length == 1)
                            {
                                checkbox2 = ((CheckBox)controleMais[0]);

                                if (checkbox2.Tag == null)
                                {
                                    //if (checkbox2.Tag.ToString() != "KNL")
                                    checkbox2.Checked = module.Plus;
                                }
                            }
                            string datamodulo;

                            if (controleMais.Length == 1)
                                datamodulo = "dtpDate" + checkbox2.Name.Replace("chk", "").Replace("Plus", "");
                            else
                                datamodulo = "dtpDate" + maismodulo.Replace("chk", "").Replace("Plus", "");

                            Control[] controleDataModulo = groupModulos.Controls.Find(datamodulo, true);

                            DateTimePicker datetimepicker = ((DateTimePicker)controleDataModulo[0]);
                            datetimepicker.Enabled = true;
                            datetimepicker.Value = module.GoodThru;
                            contadorModulo += 1;
                        }
                    }

                }
            }
            chkModulo.Checked = (27 == contadorModulo) ? true : false;
            DescricaoModulo(chkModulo);

            foreach (Control ctrl in groupModulos.Controls)
            {
                if (ctrl.GetType() == typeof(CheckBox))
                {
                    if (((CheckBox)ctrl).Appearance == Appearance.Normal)
                    {
                        //foreach (var item in listaModulos)
                        //{
                        //if (item.Monogram == ((CheckBox)ctrl).Tag.ToString())
                        // {
                        string nomemaisModulo = ((CheckBox)ctrl).Name + "Plus";
                        var chkMaisModulo = groupModulos.Controls.Find(nomemaisModulo, true);

                        if (chkMaisModulo.Length > 0)
                        {
                            if (((CheckBox)ctrl).Checked && chkKernel.Checked)
                                ((CheckBox)chkMaisModulo[0]).Enabled = true;
                            else
                                ((CheckBox)chkMaisModulo[0]).Enabled = false;
                        }
                        //}
                        //}
                    }
                }
            }


            #endregion

            grid.CurrentRow.Cells["Modules"].Value = lisModule;
        }
        private void dgvLegalIdRegistrations_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;

            if (grid.CurrentCell != null && !grid.CurrentRow.Selected)
            {
                grid.CurrentRow.Selected = true;
                dgvLegalIdRegistrations_RowHeaderMouseClick(sender, e);
            }
        }
        private void dgvLegalIdRegistrations_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            DataGridView grid = (DataGridView)sender;

            foreach (DataGridViewRow row in grid.Rows)
            {
                if (row.Cells["LegalRegistrationId"].Value != null)
                    row.Cells["LegalRegistrationId"].Value = common.FormatarCNPJ(row.Cells["LegalRegistrationId"].Value.ToString());
            }
        }

        private void txtIdLicenca_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar))
                e.Handled = true;
        }
        private void txtIdLicenca_TextChanged(object sender, EventArgs e)
        {
            Match match = Regex.Match(((TextBox)sender).Text, @"^\d+$");

            if (!match.Success)
                ((TextBox)sender).Text = "";
        }
        private void mkdCNPJ_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (common.StrongCode.Contains(e.KeyChar.ToString()))
                codeCNPJ += e.KeyChar.ToString();
        }

        private void mkdCNPJ_Click(object sender, EventArgs e)
        {
            codeCNPJ = "";
        }
        #endregion

        #endregion

        #region Metodos
        private void CarregarTipoLicenca()
        {
            cboTipoLicenca.Items.Add("");
            cboTipoLicenca.Items.Add(Sinacor.Infra.Core.Licensing.Treaty.Completa);
            cboTipoLicenca.Items.Add(Sinacor.Infra.Core.Licensing.Treaty.Modulo);
            cboTipoLicenca.Items.Add(Sinacor.Infra.Core.Licensing.Treaty.Trial);
            cboTipoLicenca.Items.Add(Sinacor.Infra.Core.Licensing.Treaty.Usuario);

            cboTipoLicenca.SelectedIndex = -1;

            cboTipoLicencaCad.Items.Add("");
            cboTipoLicencaCad.Items.Add(Sinacor.Infra.Core.Licensing.Treaty.Completa);
            cboTipoLicencaCad.Items.Add(Sinacor.Infra.Core.Licensing.Treaty.Modulo);
            cboTipoLicencaCad.Items.Add(Sinacor.Infra.Core.Licensing.Treaty.Trial);
            cboTipoLicencaCad.Items.Add(Sinacor.Infra.Core.Licensing.Treaty.Usuario);

            cboTipoLicencaCad.SelectedIndex = -1;

        }
        private void DesabilitaChecksModulosMais()
        {
            chkCadastroClientePlus.Checked = false;
            chkCadastroCliente.Checked = false;

            chkOrdensBovespaPlus.Checked = false;
            chkOrdensBovespa.Checked = false;

            chkOrdensBmfPlus.Checked = false;
            chkOrdensBmf.Checked = false;

            chkTesourariaPlus.Checked = false;
            chkTesouraria.Checked = false;

            chkContaCorrentePlus.Checked = false;
            chkContaCorrente.Checked = false;

            chkCustodiaPlus.Checked = false;
            chkCustodia.Checked = false;

            chkFaturamentoBovespaPlus.Checked = false;
            chkFaturamentoBovespa.Checked = false;

            chkFaturamentoBmfPlus.Checked = false;
            chkFaturamentoBmf.Checked = false;

            chkContabilidadePlus.Checked = false;
            chkContabilidade.Checked = false;

            chkInformacoesApoioPlus.Checked = false;
            chkInformacoesApoio.Checked = false;

            chkContasPagarPlus.Checked = false;
            chkContasPagar.Checked = false;

            chkSolicitacoesPlus.Checked = false;
            chkSolicitacoes.Checked = false;

            chkFaturamentoBTCPlus.Checked = false;
            chkFaturamentoBTC.Checked = false;

            chkIFTPlus.Checked = false;
            chkIFT.Checked = false;

            chkAcompControlePlus.Checked = false;
            chkAcompControle.Checked = false;

            chkAcompLimitesPlus.Checked = false;
            chkAcompLimites.Checked = false;

            chkCustodiaFiduciariaPlus.Checked = false;
            chkCustodiaFiduciaria.Checked = false;

            chkApuracaoIRRFPlus.Checked = false;
            chkApuracaoIRRF.Checked = false;

            chkGerArqBacenPlus.Checked = false;
            chkGerArqBacen.Checked = false;

            chkCtrlAcessoPlus.Checked = false;
            chkCtrlAcesso.Checked = false;

            chkCompliancePlus.Checked = false;
            chkCompliance.Checked = false;

            chkConefPlus.Checked = false;
            chkConef.Checked = false;

            chkSinacorHubPlus.Checked = false;
            chkSinacorHub.Checked = false;

            chkApurResultadoPlus.Checked = false;
            chkApurResultado.Checked = false;

            chkXFBPlus.Checked = false;
            chkXFB.Checked = false;

            chkOutrosPlus.Checked = false;
            chkOutros.Checked = false;

            chkKernel.Checked = false;
        }

        private static void DescricaoModulo(CheckBox checkBox)
        {
            if (checkBox.Checked)
                checkBox.Text = "Desmarca Módulos";
            else
                checkBox.Text = "Marca Módulos";
        }

        private void HabilitaDesabilitaBotoesMais(bool _parametro)
        {
            foreach (Control ctrl in this.groupModulos.Controls)
            {
                if (ctrl.GetType() == typeof(CheckBox))
                {
                    CheckBox checkBox = (CheckBox)ctrl;
                    if (checkBox.Appearance == Appearance.Button)
                    {
                        if (checkBox.Text.Contains("Mais"))
                            checkBox.Enabled = _parametro;
                    }
                }
            }
        }

        private void LimparDatas()
        {
            foreach (Control ctrl in this.groupModulos.Controls)
            {
                if (ctrl.GetType() == typeof(DateTimePicker))
                {
                    ((DateTimePicker)ctrl).Value = DateTime.Now;
                }
            }
        }

        private void LimparDataVencimento()
        {
            dtpGoodThru.Value = DateTime.Now;
            dtpGoodThru.Checked = false;
        }

        private void LimparModuloMais()
        {
            DesabilitaChecksModulosMais();
        }
        private void LimparDadosLicenciamentoPrincipal()
        {
            cboOwnerLegalRegistrationId.DataSource = null;
        }

        private void LimparDadosLicenciamento()
        {
            cboEmpresa.SelectedIndex = -1;
            mtxtLegalRegistrationId.Clear();
            txtCompanyIdSinacor.Clear();

            SelecionarDesSelecionar(false);
        }
        private void LimparGridLicenciamento()
        {
            dgvLegalIdRegistrations.DataSource = null;
        }

        private void VerificaLicencaModulo(CheckBox _modulo, CheckBox _mais, DateTimePicker _data)
        {
            if (!_modulo.Checked)
            {
                if (_mais != null)
                    _mais.Checked = false;// chkKernel.Checked;
            }
            else
            {
                if (_mais != null)
                    _mais.Enabled = chkKernel.Checked;
            }

            _data.Enabled = _modulo.Checked;
            _data.Value = DateTime.Now;

            //if(dgvLegalIdRegistrations.CurrentRow != null)
            //{
            //    //if (dgvLegalIdRegistrations.CurrentRow.Selected)
            //    //{
            //    //    dgvLegalIdRegistrations.CurrentRow.Cells["Flag"].Value = "A";

            //    //}
            //}
            VerificaModuloSelecionado();
        }

        private void AtualizaDadosEmpresa(int _indiceEmpresa)
        {
            #region Modulo
            List<Module> listModuleCompany = new List<Module>();
            Module modulo = null;
            foreach (Control ctrl in groupModulos.Controls)
            {
                if (ctrl.GetType() == typeof(CheckBox))
                {
                    if (((CheckBox)ctrl).Checked && ((CheckBox)ctrl).Appearance == Appearance.Normal)
                    {
                        foreach (var item in listaModulos)
                        {
                            if (item.Monogram == ((CheckBox)ctrl).Tag.ToString())
                            {

                                string nomemaisModulo = ((CheckBox)ctrl).Name + "Plus";
                                var chkMaisModulo = groupModulos.Controls.Find(nomemaisModulo, true);

                                //Obtem o nome do controle DatetimePicker do Modulo
                                string dataModulo = ((CheckBox)ctrl).Name.Replace("chk", "dtpDate").Replace("Plus", "");
                                var dtpControle = groupModulos.Controls.Find(dataModulo, true);

                                modulo = new Module();

                                modulo.ID = item.ID;
                                modulo.Name = item.Name;
                                modulo.Monogram = item.Monogram;

                                if (chkMaisModulo.Length == 1)
                                {
                                    if (((CheckBox)chkMaisModulo[0]).Enabled)
                                        modulo.Plus = ((CheckBox)chkMaisModulo[0]).Checked;
                                    else
                                        modulo.Plus = true;
                                }
                                if (dtpControle.Length == 1)
                                    modulo.GoodThru = Convert.ToDateTime(dtpControle[0].Text);

                                listModuleCompany.Add(modulo);
                                break;
                            }
                        }
                    }
                }
            }
            #endregion
            if (listModuleCompany.Count != 0)
                dgvLegalIdRegistrations.Rows[_indiceEmpresa].Cells["Modules"].Value = listModuleCompany;
        }

        private bool ValidarDadosLicenciamento()
        {
            DateTime goodThru = dtpGoodThru.Value;
            int companyIdSinacor = string.IsNullOrEmpty(txtCompanyIdSinacor.Text) ? 0 : Convert.ToInt32(txtCompanyIdSinacor.Text);
            Company companyAux = (Company)cboEmpresa.SelectedItem;

            string companyName = "";

            string legalregistrationid = common.ValorControle(mtxtLegalRegistrationId);

            if (companyAux != null)
            {
                if (companyAux.CompanyId.HasValue)
                {
                    companyName = companyAux.Name;
                }
            }

            #region Validação
            #region Campos Obrigatórios
            if (string.IsNullOrEmpty(companyName))
            {
                MessageBox.Show("Informe o " + lblCompanyName.Text);
                cboEmpresa.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(legalregistrationid))
            {
                MessageBox.Show("Informe o " + lblLegalRegistrationId.Text);
                mtxtLegalRegistrationId.Focus();
                return false;
            }
            if (companyIdSinacor == 0)
            {
                MessageBox.Show("Informe o " + lblCompanyIdSinacor.Text);
                txtCompanyIdSinacor.Focus();
                return false;
            }
            #endregion
            #endregion

            return true;
        }

        private List<Module> ValidarEmpresaModulo()
        {
            #region Modulo
            List<Module> listModuleCompany = new List<Module>();
            Module modulo = null;
            foreach (Control ctrl in groupModulos.Controls)
            {
                if (ctrl.GetType() == typeof(CheckBox))
                {
                    if (((CheckBox)ctrl).Checked && ((CheckBox)ctrl).Appearance == Appearance.Normal && ((CheckBox)ctrl).Tag.ToString() != "")
                    {
                        foreach (var item in listaModulos)
                        {
                            if (item.Monogram == ((CheckBox)ctrl).Tag.ToString())
                            {
                                string nomemaisModulo = ((CheckBox)ctrl).Name + "Plus";
                                var chkMaisModulo = groupModulos.Controls.Find(nomemaisModulo, true);

                                //Obtem o nome do controle DatetimePicker do Modulo
                                string dataModulo = ((CheckBox)ctrl).Name.Replace("chk", "dtpDate").Replace("Plus", "");
                                var dtpControle = groupModulos.Controls.Find(dataModulo, true);

                                modulo = new Module();

                                modulo.ID = item.ID;
                                modulo.Name = item.Name;
                                modulo.Monogram = item.Monogram;

                                if (chkMaisModulo.Length > 0)
                                {
                                    if (((CheckBox)chkMaisModulo[0]).Enabled)
                                        modulo.Plus = ((CheckBox)chkMaisModulo[0]).Checked;
                                    else
                                        modulo.Plus = false;
                                }
                                modulo.GoodThru = Convert.ToDateTime(dtpControle[0].Text);

                                listModuleCompany.Add(modulo);
                                break;
                            }
                        }
                    }
                }
            }
            if (listModuleCompany.Count == 0)
                MessageBox.Show("Selecione algum módulo");
            #endregion
            return listModuleCompany;
        }

        private bool ValidaRegistroSelecionado(int _indice)
        {
            List<CheckBox> listCheckModulos = new List<CheckBox>();

            if (dgvLegalIdRegistrations.Rows[_indice].Cells["Name"].Value == null)
                cboEmpresa.SelectedText = "";
            else
                cboEmpresa.SelectedText = dgvLegalIdRegistrations.Rows[_indice].Cells["Name"].Value.ToString();

            if (dgvLegalIdRegistrations.Rows[_indice].Cells["LegalRegistrationId"].Value == null)
                mtxtLegalRegistrationId.Text = "";
            else
                mtxtLegalRegistrationId.Text = dgvLegalIdRegistrations.Rows[_indice].Cells["LegalRegistrationId"].Value.ToString();

            if (dgvLegalIdRegistrations.Rows[_indice].Cells["SinacorCompanyId"].Value == null)
                txtCompanyIdSinacor.Text = "";
            else
                txtCompanyIdSinacor.Text = dgvLegalIdRegistrations.Rows[_indice].Cells["SinacorCompanyId"].Value.ToString();

            if (!ValidarDadosLicenciamento())
            {
                dgvLegalIdRegistrations.Rows[_indice].Selected = true;
                return false;
            }

            List<Module> lisModule = ValidarEmpresaModulo();

            if (lisModule.Count == 0)
            {
                dgvLegalIdRegistrations.Rows[_indice].Selected = true;
                return false;
            }
            else
            {
                if (licensing.Companies.Count != 0)
                {
                    //                       PreencheDataVencimentoModulo();
                    lisModule = ValidarEmpresaModulo();

                    licensing.Companies[_indice].Modules = lisModule;
                    //SelecionarDesSelecionar(false);
                }
                else
                {
                    if (lisModule.Count != 0)
                        dgvLegalIdRegistrations.Rows[_indice].Cells["Modules"].Value = lisModule;
                }
            }
            return true;
        }

        private void SelecionarDesSelecionar(bool _paramtro)
        {
            foreach (Control ctrl in this.groupModulos.Controls)
            {
                if (ctrl.GetType() == typeof(CheckBox))
                {
                    CheckBox checkBox = (CheckBox)ctrl;

                    if (checkBox.Appearance == Appearance.Normal && checkBox.Tag.ToString() != "")
                        checkBox.Checked = _paramtro;

                    if (checkBox.Appearance == Appearance.Button && checkBox.Text.ToString() == "Mais")
                        checkBox.Checked = _paramtro;
                }
            }
        }

        private void CarregarEmpresa()
        {
            cboEmpresa.DataSource = null;
            company = new Company();
            listaEmpresa.Insert(0, company);

            cboEmpresa.DisplayMember = "Name";
            cboEmpresa.ValueMember = "CompanyId";
            cboEmpresa.DataSource = listaEmpresa;

        }

        private void CarregarOwnerLegalRegistrationId()
        {
            cboOwnerLegalRegistrationId.DataSource = null;

            listaCNPJ.Insert(0, "");

            cboOwnerLegalRegistrationId.DataSource = listaCNPJ;

        }
        private void SelecionarOwnerLegalRegistrationId(string _valor)
        {
            int indexCombo = -1;
            for (int indice = 0; indice < listaCNPJ.Count; indice++)
            {
                if (listaCNPJ[indice] == _valor)
                {
                    indexCombo = indice;
                    break;
                }
            }
            cboOwnerLegalRegistrationId.SelectedIndex = indexCombo;
        }

        private void AtualizaListaCNPJ()
        {
            listaCNPJ.Clear();
            string cnpjAux = "";
            bool encontrarCNPJ = false;

            if (listaCompany != null)
            {
                foreach (var item in listaCompany)
                {
                    cnpjAux = common.FormatarCNPJ(item.LegalRegistrationId);

                    if (listaCNPJ.Count == 0)
                    {
                        if (!string.IsNullOrEmpty(common.DesformatarCNPJ(cnpjAux)))
                            listaCNPJ.Add(cnpjAux);
                    }
                    else
                    {
                        foreach (string itemCNPJ in listaCNPJ)
                        {
                            if (itemCNPJ.Contains(cnpjAux) || string.IsNullOrEmpty(common.DesformatarCNPJ(cnpjAux)))
                            {
                                encontrarCNPJ = true;
                                break;
                            }
                        }
                        if (!encontrarCNPJ)
                            listaCNPJ.Add(cnpjAux);
                    }
                }
            }
            listaCNPJ.Sort();
            string cnpj = "";

            if (Convert.ToString(cboOwnerLegalRegistrationId.SelectedItem) != "")
                cnpj = cboOwnerLegalRegistrationId.SelectedItem == null ? "" : cboOwnerLegalRegistrationId.SelectedItem.ToString();
            else
                cnpj = common.FormatarCNPJ(licensing.OwnerLegalRegistrationId);

            CarregarOwnerLegalRegistrationId();

            SelecionarOwnerLegalRegistrationId(cnpj);
        }
        public void AtualizarEmpresas(Company _company)
        {
            if (_company != null)
            {
                Company companyAux = null;
                if (listaCompany != null)
                    companyAux = listaCompany.Find(match => match.CompanyId == _company.CompanyId);
                bool retorno = false;

                if (companyAux != null)
                    retorno = listaCompany.Remove(companyAux);

                if (retorno)
                {
                    dgvLegalIdRegistrations.DataSource = null;
                    dgvLegalIdRegistrations.AutoGenerateColumns = false;
                    dgvLegalIdRegistrations.DataSource = listaCompany;

                    atualizarDataModulos = false;
                    #region Limpar Dados
                    LimparDadosLicenciamento();
                    LimparModuloMais();
                    LimparDatas();

                    #endregion
                    atualizarDataModulos = true;

                    indiceLegalIdRegistrations = null;
                    dgvLegalIdRegistrations.CurrentRow.Selected = false;
                }
            }
            listaEmpresa = bussinesEmpresa.Selecionar(pesquisaCompany);
            CarregarEmpresa();
        }

        private void HabilitarDesabilitarBotoes(bool _parametro)
        {
            btnHistorico.Enabled = _parametro;
            btnExportar.Enabled = _parametro;
            btnDelete.Enabled = _parametro;
        }

        private void CarregaListaLicencaBKP()
        {
            listaLicencaBKP.Clear();
            Licensing licensingbkp;
            Company companybkp;
            Module modulebkp;

            listaLicencaBKP.Clear();

            foreach (Licensing licenca in listaLicenca)
            {
                licensingbkp = licenca.Clone() as Licensing;

                if (licenca.Companies != null)
                {
                    licensingbkp.Companies = new List<Company>();

                    foreach (Company empresa in licenca.Companies)
                    {
                        companybkp = empresa.Clone() as Company;
                        companybkp.Modules = new List<Module>();
                        foreach (Module modulo in empresa.Modules)
                        {
                            modulebkp = new Module();

                            modulebkp.ID = modulo.ID;
                            modulebkp.Monogram = modulo.Monogram;
                            modulebkp.GoodThru = modulo.GoodThru;

                            modulebkp.Name = modulo.Name;
                            modulebkp.Plus = modulo.Plus;

                            companybkp.Modules.Add(modulebkp);
                        }

                        licensingbkp.Companies.Add(companybkp);
                    }
                }


                listaLicencaBKP.Add(licensingbkp);
            }
        }

        private void CarregaListaLicenca()
        {
            Licensing licensingbkp;
            Company companybkp;
            Module modulebkp;

            listaLicenca.Clear();

            foreach (Licensing licenca in listaLicencaBKP)
            {
                licensingbkp = licenca.Clone() as Licensing;

                licensingbkp.Companies = new List<Company>();
                foreach (Company empresa in licenca.Companies)
                {
                    companybkp = empresa.Clone() as Company;
                    companybkp.Modules = new List<Module>();
                    foreach (Module modulo in empresa.Modules)
                    {
                        modulebkp = new Module();

                        modulebkp.ID = modulo.ID;
                        modulebkp.Monogram = modulo.Monogram;
                        modulebkp.GoodThru = modulo.GoodThru;

                        modulebkp.Name = modulo.Name;
                        modulebkp.Plus = modulo.Plus;

                        companybkp.Modules.Add(modulebkp);
                    }

                    licensingbkp.Companies.Add(companybkp);
                }

                listaLicenca.Add(licensingbkp);
            }
        }

        private void VerificaModuloSelecionado()
        {
            int contadoModulo = 0;
            foreach (Control ctrl in this.groupModulos.Controls)
            {
                if (ctrl.GetType() == typeof(CheckBox))
                {
                    CheckBox checkBox = (CheckBox)ctrl;
                    if (checkBox.Appearance == Appearance.Normal && checkBox.Tag.ToString() != "")
                    {
                        if (checkBox.Checked)
                            contadoModulo += 1;
                    }
                }
            }
            //chkModulo.Checked = (listaModulos.Count == contadoModulo) ? true : false;
            chkModulo.Checked = (27 == contadoModulo) ? true : false;
            DescricaoModulo(chkModulo);
        }

        private void VerificaMaisSelecionado()
        {
            int contadoMais = 0;
            foreach (Control ctrl in this.groupModulos.Controls)
            {
                if (ctrl.GetType() == typeof(CheckBox))
                {
                    CheckBox checkBox = (CheckBox)ctrl;
                    if (checkBox.Appearance == Appearance.Button)
                    {
                        if (checkBox.Checked)
                            contadoMais += 1;
                    }
                }
            }
            // chkKernel.Checked = (26 == contadoMais) ? true : false;
            //chkModulo.Checked = chkKernel.Checked;
            DescricaoModulo(chkModulo);
        }

        #endregion

        private void btnTrocar_Click(object sender, EventArgs e)
        {
            PreencheDataVencimentoModulo();
        }
    }
}
